<?php
namespace app\crm\traits;

use jianyan\excel\Excel;
use EasyAdmin\Tool;
use think\Db;

trait Curd
{
    /**
     * @NodeAnotation(title="列表")
     */    
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        // 1.验证请求方式
        if ($this->request->isPost()) {
            // 2.获取请求数据
            $post = $this->request->post();
            $validate = new $this->validate();
            if ($validate->check($post) == false) 
                return $this->error($validate->getError());
           
            $result = $this->model->allowField(true)->save($post);
            if( !$result ){
                return $this->error('保存失败');
            }
            return $this->success('保存成功');
        }
        return $this->fetch('form');
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        // 1.验证请求方式
        if ($this->request->isPost()) {
            // 2.获取请求数据
            $post = $this->request->post(); 
            $validate = new $this->validate();
            if ($validate->check($post) == false) 
                return $this->error($validate->getError());
           
            $id = $this->request->param('id');
            $where['id']= $id;
            $result = $this->model->allowField(true)->save($post,$where);
            if( !$result ){
                return $this->error('保存失败');
            }
            return $this->success('保存成功');
        }
        $list = $this->model->where('id',$id)->find();
        return $this->fetch('form',['data'=>$list]);
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete()
    {
        $ids = $this->request->param('id/a');
        if (empty($ids)) {
            return $this->error('缺少id参数');
        }
        $rows = $this->model->whereIn('id',$ids)->select();
        foreach($rows as $row){
            $row->delete(false);
        }
        return $this->success('删除成功', '');
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        var_dump($page, $limit, $where);exit;
        $tableName = $this->model->getName();
        $tableName = Tool::humpToLine(lcfirst($tableName));
        $prefix = config('database.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFields)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $this->checkPostRequest();
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     * @NodeAnotation(title="回收站")
     */    
    public function recycle()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model->onlyTrashed()
                ->where($where)
                ->count();
            $list = $this->model->onlyTrashed()
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                //->fetchSql()
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="数据还原")
     */ 
    public function restore()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post('id/a');
            Db::startTrans();
            try {
                foreach($ids as $id) {
                    $obj = $this->model::onlyTrashed()->find($id);
                    if($obj->restore() == false){
                        throw new \Exception('数据还原失败');
                    }
                }
                Db::commit();
                return json(['code' => 1, 'msg' => '数据还原成功']);
            } catch (\think\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
                return json(['code' => 0, 'msg' => '数据还原失败']);
            }
        }
    }

    /**
     * @return null 放入线索池、公海客户
     */
    public function discard()
    {
        $ids = $this->request->param('id/a');
        if (empty($ids)) {
            return $this->error('缺少id参数');
        }
        $this->model->whereIn('id',$ids)->update(['owner_user_id' => 0]);
        return $this->success('操作成功', '');
    }


    /**
     * @return null 线索转客户
     */
    public function turnCustomer()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return $this->error('缺少id参数');
        }
        $this->model->update(['id' => $id,'status' => 2]);
        return $this->success('转成客户成功', '');
    }
}